# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from time import sleep

import requests
from PIL import Image
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

from supereagle import SuperEagleClient

headers = {
    'Users-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                   'Chrome/94.0.4606.71 Safari/537.36 '
}


def get_coordinates(eagle_result):
    all_list = []  # 要存储即将被点击的点的坐标  [[x1,y1],[x2,y2]]
    if '|' in eagle_result:
        coordinates = eagle_result.split('|')
        coordinates_count = len(coordinates)
        for num in range(coordinates_count):
            xy_list = []
            x = int(coordinates[num].split(',')[0])
            y = int(coordinates[num].split(',')[1])
            xy_list.append(x)
            xy_list.append(y)
            all_list.append(xy_list)
    else:
        x = int(eagle_result.split(',')[0])
        y = int(eagle_result.split(',')[1])
        xy_list = [x, y]
        all_list.append(xy_list)

    return all_list


# 不自动关闭浏览器
option = webdriver.ChromeOptions()
option.add_experimental_option("detach", True)

# 注意此处添加了chrome_options参数
driver = webdriver.Chrome(options=option)
driver.get('https://passport.bilibili.com/login')

# 定位用户名，密码输入框
username = driver.find_element(by=By.ID, value='login-username')
password = driver.find_element(by=By.ID, value='login-passwd')
username.send_keys('18959482985')
password.send_keys('DSHBlack39')
# 定位登录按钮并点击
print('click login...')
driver.find_element(by=By.XPATH, value='//div[@class="btn-box"]/a[@class="btn btn-login"]').click()

# 验证码
try:
    # //div[@class="geetest_item_wrap"]/img
    img_element: WebElement = WebDriverWait(driver, 5, 0.5).until(
        EC.presence_of_element_located(
            (By.XPATH, '/html/body/div[2]/div[2]/div[6]/div/div/div[2]/div[1]/div/div[2]/img')),
        message='验证码图片获取失败!')
except Exception as e:
    driver.close()
    print(str(e))
    exit(2)
else:
    sleep(1)
    img_url = img_element.get_attribute('src')
    print(str(img_url))
    img_byte = requests.get(url=img_url, headers=headers).content
    with open('./gee_test.png', 'wb') as fp:
        fp.write(img_byte)
    i = Image.open('./gee_test.png')
    # 转化为实际渲染大小
    img = i.resize((259, 290))
    img.save('./gee_test.png')

    # 识别验证码
    eagle = SuperEagleClient('sleepymangosteen', 'DSHBlack39', '927874')
    im = open('gee_test.png', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    # 9004是验证码类型
    result = eagle.PostPic(im, 9004)['pic_str']
    # print(result)

    # 点击验证码
    coordinate_list = get_coordinates(result)
    print('coordinates' + str(coordinate_list))
    for coordinate in coordinate_list:
        # 乘缩放比例
        x_offset = int(coordinate[0])
        y_offset = int(coordinate[1] * 1.12)
        print('click: ' + str(x_offset) + ',' + str(y_offset))
        ActionChains(driver).move_to_element_with_offset(img_element, x_offset, y_offset).click().perform()
        sleep(1)

    driver.find_element(by=By.XPATH, value='//div[@class="geetest_panel"]/a[@class="geetest_commit"]').click()

# urls = driver.find_elements(by='xpath', value='//a[@href]')
# # noinspection PyTypeChecker
# print('\n'.join([url.get_attribute('href') for url in urls]))
